package servlet;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import database.DBConnection;

/**
 * 添加新词到字典servlet
 * @author Da Huang (dhuang.cn@gmail.com)
 *
 */
public class AddDict extends HttpServlet {

	private static final long serialVersionUID = 2405559836106569082L;

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		int numOfNewWords = Integer.parseInt(req.getParameter("numOfNewWords"));
		
		try {
			Connection conn = DBConnection.getConnection();
			PreparedStatement pstmtSet = conn.prepareStatement(
					"UPDATE `dict` SET `type` = ? WHERE `name` = ?");
			PreparedStatement pstmtIns = conn.prepareStatement(
					"INSERT INTO `dict`(`name`, `type`) VALUES(?, ?)");
			for (int i = 0; i < numOfNewWords; i ++) {
				String name, type;
				name = new String(req.getParameter("new-word-" + i + "-name").getBytes("ISO8859-1"), "UTF-8");
				type = new String(req.getParameter("new-word-" + i + "-type").getBytes("ISO8859-1"), "UTF-8");
//				System.out.println(name + " " + type);
				try {
					/* 先尝试插入记录 */
					pstmtIns.setString(1, name);
					pstmtIns.setString(2, type);
					pstmtIns.executeUpdate();
				} catch (SQLException e) {
					/* 记录插入失败，就采取更新方式 */
					pstmtSet.setString(1, type);
					pstmtSet.setString(2, name);
					pstmtSet.executeUpdate();
				}
			}
			pstmtSet.close();
			pstmtIns.close();
			conn.close();
			
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
}
